package co.angluzha.commons.core.listener;

import org.slf4j.MDC;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * co.angluzha.commons.core.listener文档说明
 *
 * @author Angluzha
 * @version 2022/11/21
 */
public class LogMDCListener implements GenericApplicationListener{

    @Override
    public boolean supportsEventType(ResolvableType resolvableType) {

        return resolvableType.isAssignableFrom(ApplicationEnvironmentPreparedEvent.class);

    }

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        ApplicationEnvironmentPreparedEvent event = (ApplicationEnvironmentPreparedEvent) applicationEvent;
        ConfigurableEnvironment environment = event.getEnvironment();
        String serverName = environment.getProperty("spring.application.name");

        MDC.put("serverName",serverName);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE+19;
    }
}
